const url = 'http://www.xiongmaoyouxuan.com/';

const block = {
    activeTab: 'tab1',
    data: {
        tab1: {
            loadWay: 'loadmore',
            loading: false,
            firstMore: true,
            finish: false,
            api: 'api/tab/1',
            items: [],
            bannersURl: [],
            pageSize: 0,
            presentApi: 0,
            history: 0
        },
        tab2: {
            loadWay: 'loadmore',
            loading: false,
            finish: false,
            firstMore: true,
            api: ['api/sub_column/7/items', 'api/sub_column/1/items', 'api/sub_column/2/', 'api/sub_column/3/items', 'api/sub_column/4/items', 'api/sub_column/5/items', 'api/sub_column/6/items', 'api/sub_column/50/items'],
            tabTitleApi: 'api/column/29',
            items: [],
            tabTitleListIsExist: false,
            pageSize: 0,
            presentApi: 0,
            history: 0
        },
        tab3: {
            loadWay: 'loadmore',
            loading: false,
            finish: false,
            tabTitleListIsExist: false,
            firstMore: true,
            api: ['api/sub_column/174/items', 'api/sub_column/175/items', 'api/sub_column/176/items', 'api/sub_column/177/items', 'api/sub_column/178/items'],
            tabTitleApi: 'api/column/170',
            items: [],
            pageSize: 0,
            presentApi: 0,
            history: 0
        },
        tab4: {
            loadWay: 'loadmore',
            loading: false,
            finish: false,
            firstMore: true,
            tabTitleListIsExist: false,
            api: 'api/column/3183/items',
            tabTitleApi: 'api/column/3183',
            items: [],
            pageSize: 0,
            presentApi: 0,
            history: 0
        }
    },
    init: function () {

        $('.btn-more').click(function () {
            this.loadMore(this.renderItems)
            $('.btn-more').hide()
            this.data[this.activeTab].firstMore = false;
        }.bind(this))

        window.addEventListener('scroll', function () {
            if (this.data[this.activeTab].firstMore) return
            const html = document.documentElement;
            const scrollTop = html.scrollTop;
            const scrollHeight = html.scrollHeight;
            const innerHeight = window.innerHeight;
            if (scrollTop + innerHeight >= scrollHeight - 100) {
                this.loadMore(this.renderItems)
            }
        }.bind(this), false)

        this.fetchData(this.renderItems.bind(this))

        // 跳轉詳情頁
        $('.choice-list').on('click', '.choice-item', function () {
            const id = $(this).attr('data-id')
            block.openDetali(id)
        })
    },
    getActiveTab: function () {
        return this.data[this.activeTab]
    },
    fetchApi: function () {
        const active = this.getActiveTab();
        if (!(active.api instanceof Array)) return active.api
        return active.api[active.presentApi]
    },
    checkHistory: function () {
        const active = this.getActiveTab();
        return active.history > active.pageSize
    },
    fetchData: function (callback) {
        const active = this.getActiveTab();
        if (active.loading) return
        if (this.checkHistory()) {
            return callback(active.items)
        }
        this.loadingStart()
        const api = this.fetchApi()
        $.ajax({
            url: url + api,
            type: 'GET',
            dataType: 'JSON',
            data: {
                start: active.pageSize,
                sort: 0
            },
            success: function (res) {
                this.loadingEnd()
                if (res.data.isEnd) {
                    active.finish = true
                    return
                }
                if (res.data.banners && active.bannersURl) {
                    active.bannersURl = res.data.banners.map(function (el, i) {
                        return el.imageUrl
                    })
                }
                if (res.data.items) {
                    active.items = active.items.concat(this.formatItems(res.data.items.list))
                    callback(this.formatItems(res.data.items.list))
                } else {
                    active.items = active.items.concat(this.formatItems(res.data.list))
                    callback(this.formatItems(res.data.list))
                }
                active.pageSize += 20;
                if (active.history <= active.pageSize) {
                    active.history = active.pageSize
                }
            }.bind(this)
        })

    },
    formatItems: function (data) {
        let arr = [];
        data.forEach(function (el, i) {
            if (el.title) {
                const itemsObj = {
                    title: el.title,
                    hasCoupon: el.hasCoupon,
                    couponValue: el.couponValue,
                    isFreePostage: el.isFreePostage,
                    saleNum: el.saleNum >= 10000 ? (el.saleNum / 1000).toFixed(1) + '万' : el.saleNum,
                    priceStrong: el.price.toString().split('.')[0],
                    priceDigit: el.price.toString().split('.')[1],
                    image: el.image,
                    type: el.type === 1 ? '天猫' : '淘宝',
                    typeClass: el.type === 1 ? 'tmall' : 'taobao',
                    id: el.id
                }
                arr.push(itemsObj)
            }
        })
        return arr
    },
    loadMore: function (callback) {
        const active = this.getActiveTab()
        active.loadWay = 'loadmore';
        this.fetchData(callback.bind(this))
    },
    renderItems: function (data) {
        const active = this.getActiveTab();
        // 首页渲染且没有初始化swiper
        if (this.activeTab === 'tab1' && !this.swiper) {
            this.bannersInitAnRender()
            // 分页渲染且分页title没有初始化
        } else if (!active.tabTitleListIsExist) {
            this.tabTitleAndSubListRender()
        }
        const main = document.querySelector('.choice-list');
        const html = [];
        data.forEach(function (el, i) {
            let itemsHtml = template('items', el)
            html.push(itemsHtml)
        })
        // main.insertAdjacentHTML('beforeend', html.join(''));
        main.innerHTML += html.join('');

    },
    bannersInitAnRender: function () {
        const banners = {
            arr: this.data.tab1.bannersURl
        }
        const bannerHtml = template('bannerBox', banners)
        $('.nav').after(bannerHtml)
        this.swiper = new Swiper('.swiper-container', {
            direction: 'horizontal', // 垂直切换选项
            loop: true, // 循环模式选项

            // 如果需要分页器
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },

            // 如果需要前进后退按钮
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            // 自动播放
            autoplay: true
        })
    },
    tabTitleAndSubListRender: function () {
        const active = this.getActiveTab()
        $.ajax({
            url: url + active.tabTitleApi,
            type: 'GET',
            dataType: 'JSON',
            success: function (res) {
                if (res.code && res.data) {
                    const tabLIst = {
                        arr: res.data.subColumns.map(function (el, i) {
                            return el.name
                        }),
                        title: res.data.name
                    }
                    const html = template('tabList', tabLIst)
                    $('.nav').after(html)
                    $('.tab-item').eq(0).addClass('active')
                    $('.tab-item').click(function () {
                        const index = $(this).index()
                        $(this).addClass("active").siblings().removeClass("active");
                        active.presentApi = index;
                        block.fetchData.call(block, block.renderItems.bind(block))
                        $('.choice-list').html('')
                        active.pageSize = 0;
                    })
                    active.tabTitleListIsExist = true
                }
            }.bind(this)
        })
    },
    loadingStart: function () {
        const load = document.getElementById('load');
        this.data[this.activeTab].loading = true
        load.classList.add('loading');
    },
    loadingEnd: function (active) {
        const load = document.getElementById('load');
        this.data[this.activeTab].loading = false
        load.classList.remove('loading');
    },
    tabChangeInit: function () {
        $('.choice-list').html('')
        if ($('#main')) {
            $('#main').remove();
            this.swiper = null
        }
        if ($('#tab-nav')) {
            $('#tab-nav').remove()
        }
        const active = this.getActiveTab();
        active.finish = false;
        active.firstMore = true;
        active.tabTitleListIsExist = false;
        active.pageSize = 0;
        active.presentApi = 0;
        $('.btn-more').show()
    },
    openDetali: function (id) {
        window.open('../demo/details.html'+`?id=${id}`)
    }
}

const route = {
    hash: '',
    init: function () {
        $('.nav-list').on('click', '.list-item', function () {
            location.hash = $(this).attr('data-hash')
            $('.list-item').removeClass('active')
            $(this).addClass('active');
        })
        this.hashChange()
    },
    hashChange: function () {
        window.addEventListener('hashchange', function () {
            this.hash = location.hash.substr(1);
            if (this.hash === '') {
                this.hash = 'tab1'
            }
            block.activeTab = this.hash;
            this.path[this.hash]()
        }.bind(this), false)
    },
    path: {
        'tab1': function () {
            block.tabChangeInit.call(block)
            block.fetchData(block.renderItems.bind(block))
        },
        'tab2': function () {
            block.tabChangeInit.call(block)
            block.fetchData(block.renderItems.bind(block))
        },
        'tab3': function () {
            block.tabChangeInit.call(block)
            block.fetchData(block.renderItems.bind(block))
        },
        'tab4': function () {
            block.tabChangeInit.call(block)
            block.fetchData(block.renderItems.bind(block))
        }
    }
}

block.init()
route.init()
// backTop
$(window).scroll(function () {
    if ($(this).scrollTop() > 200) {
        $('#back_top').show()
    } else {
        $('#back_top').hide()
    }
})

$('#back_top').on('click', function () {
    $('body,html').animate({
        scrollTop: 0
    }, 1000)
})